package com.jse.interceptor;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.log4j.Logger;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class JseInterceptor implements HandlerInterceptor {
	
	private static final Logger log = Logger.getLogger(JseInterceptor.class);
	
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	long start_time = System.currentTimeMillis();
    	request.setCharacterEncoding("utf-8");
    	request.setAttribute("jse_start_time", start_time);
    	NutMap param=new NutMap();
    	request.getParameterMap().forEach((k,v)->{
			if(v!=null) {
				param.put(k, v.length>1?Arrays.asList(v):v[0]);
			}else {
				
			}
		});
    	if(request.getContentType()!=null&&request.getContentType().contains("multipart/form-data")) {
    		request.getParts().forEach(part->{
    			String name = part.getName();  
                String fileName = getFilename(part);  
    			if (!Strings.isEmpty(fileName)) {
                    String str = request.getServletContext().getRealPath("/").replace("\\", "/");
            		String appName = str.substring(0, str.lastIndexOf("/"));
            		appName = appName.substring(appName.lastIndexOf("/"));
            		String webPath = str.substring(0, str.indexOf("tomcat") + 7) + "webapps/";
            		String filePath = str.substring(0, str.indexOf("tomcat") + 7) + "webapps/upload/file";
            		try {
            			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            			String dateString = simpleDateFormat.format(new Date());
            			String fid = UUID.randomUUID().toString();
            			filePath = filePath +appName+"/" +  dateString + "/" + fid+"_" + fileName;
            			File f1=new File(filePath);
            			new File(f1.getParent()).mkdirs();
            			part.write(filePath);
            			filePath = filePath.replace(webPath, "");
            			param.put(name, filePath);
            		} catch (Exception e) {
            			log.error("file upload copy fail! err_msg :", e);
            		}
                }
    		});
    	}
    	request.setAttribute("p", param);
        return true;
    }
    
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

    @Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		long start_time = (Long)request.getAttribute("jse_start_time");
		request.removeAttribute("jse_start_time");
        long end_time = System.currentTimeMillis();
        long executeTime = end_time - start_time;
        log.info(handler + " execute time :" + executeTime + "ms");
	}
    
    private String getFilename(Part part) {  
        String contentDispositionHeader =   
                part.getHeader("content-disposition");  
        String[] elements = contentDispositionHeader.split(";");  
        for (String element : elements) {  
            if (element.trim().startsWith("filename")) {  
                return element.substring(element.indexOf('=') + 1)  
                        .trim().replace("\"", "");  
            }  
        }  
        return null;  
    }

}
